$  ->
    $.ajaxPrefilter((options, origOptions, req) ->
        url = options.url
        url += if url.match(/\?/) then '&' else '?'
        url += '__ajax_req=1'
        options.url = url
    );

    $.ajaxSetup(
        type: 'post',
        beforeSend: () ->
            throbberShow()
        complete: () ->
            throbberHide()
    );

    initRemoteLinks()


initRemoteLinks = (elements=$('[data-remote=true]')) ->

    elements.each () ->
        return if $(this).data('inited')

        $(this).click () ->
            cfrm = $(this).data('confirm')
            if cfrm
                return if !confirm(cfrm)

            options =
                url: $(this).data('url')

            data = $(this).data('data')
            if data
                options['data'] = JSON.parse(data)
                options['type'] = 'post'

            before = $(this).data('before')
            if before
                options['beforeSend'] = () ->
                    eval(before)

            complete = $(this).data('complete')
            if complete
                options['complete'] = (req) ->
                    eval(complete)

            location.hash = '!'+$(this).data('url')
            $.ajax(options)
            return false

        $(this).data('inited', true)

throbberHide = () ->
    $('#throbber').animate 
        top: -40

throbberShow = () ->
    $('#throbber').animate
        top: 0

locationHash = (handler, urlParser) ->
    if location.hash
        url = location.hash.replace /^#!/, ''
        if urlParser?
            url = urlParser.call this, url
        $.ajax
            url: url,
            complete: handler

htmlEditor = (expr) ->
    tinymce.init
        selector: expr,
        menubar: false,
        relative_urls: false,
        plugins: ['link', 'fullscreen'],
        toolbar: "formatselect | bold italic underline | alignleft aligncenter alignright alignjustify | "+
                 "cut copy paste | bullist numlist | outdent indent | link unlink | fullscreen"